package com.dgut.aop;

import com.dgut.controller.LogController;
import com.dgut.domain.Log;
import com.dgut.service.ILogService;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

public class LogAdvice {


//hkjh
    //开启日志时间
    private Date startDate;
    @Autowired
    private ILogService service;
    @Autowired
    private HttpServletRequest request;

    public void logBefore(JoinPoint joinPoint) throws NoSuchMethodException {


        System.out.println("logBefore");
        startDate = new Date();
    }

    public void  logAfter(JoinPoint joinPoint) throws NoSuchMethodException {


        //获取当前访问的类
        Class aClass = joinPoint.getTarget().getClass();
        if (aClass == LogController.class){
            return;
        }
        //获取当前访问的类上面的RequestMapping注解
        RequestMapping requestMapping = (RequestMapping) aClass.getAnnotation(RequestMapping.class);
        //获取当前访问的类上面的RequestMapping注解的值"/account"
        String classValue = requestMapping.value()[0];
        //获取传过来的参数
        Object[] args = joinPoint.getArgs();
        //保存参数的类型
        Class[] classesArgs = new Class[args.length];
        for (int i = 0 ;i < args.length;i++){
            classesArgs[i] = args[i].getClass();
        }
        //获取当前访问的方法的名字
        String methodName = joinPoint.getSignature().getName();
        Method method = aClass.getMethod(methodName, classesArgs);
        RequestMapping methodRequestMapping = method.getAnnotation(RequestMapping.class);
        String methodValue = methodRequestMapping.value()[0];
        System.out.println(classValue+methodValue);


        System.out.println("logAfter");
        long during = new Date().getTime() - startDate.getTime();
        Log log = new Log();
        log.setContent("执行了【AccountController】中的-trans方法");
        log.setVisitTime(startDate);
        log.setIp(request.getLocalAddr());
        log.setDuring(during);
        log.setUrl(classValue+methodValue);
        service.insert(log);
    }
}
